﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ExplorerPlus.DomainObjects;
using ExplorerPlus.PersistenceLayer;
using ExplorerPlus.PluginsInterface;
using ExplorerPlus.Utilities;

namespace ExplorerPlus
{
    public partial class SearchOnline : Form
    {
        Categories selectedCategory;
        IWebSearchPlugin webSearchPlugin;
        public Item item;

        public SearchOnline(Categories defaultCategory)
        {
            InitializeComponent();
            this.selectedCategory = defaultCategory;
            this.Text += " - " + defaultCategory.ToString();
        }

        public SearchOnline(Categories defaultCategory, string keyword) : this(defaultCategory)
        {
            this.txtKeyword.Text = keyword;
        }

        public void SetKeyword(string keyword)
        {
            this.txtKeyword.Text = keyword;
        }

        private void SearchOnline_Load(object sender, EventArgs e)
        {
            //List<FlyWeightItem> categories = PersistenceLayerFacade.GetFlyWeightCategories();
            //lstCategory.DataSource = categories;
            //lstCategory.ValueMember = "Id";
            //lstCategory.DisplayMember = "Name";
            //lstCategory.SelectedValue = selectedCategory;
            AmazonApi.AmazonClient.SetAmazonLocales(Configuration.ConfigurationSettings.AppSettings.AmazonLocales);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (LoadWebSearchPlugin())
            {
                btnSearch.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                try
                {
                    string[] columns = webSearchPlugin.GetSearchColumns();
                    List<string[]> results = webSearchPlugin.Search(txtKeyword.Text);
                    this.SuspendLayout();
                    lstItems.SuspendLayout();
                    lstItems.Clear();
                    foreach (string col in columns)
                    {
                        lstItems.Columns.Add(col);
                    }
                    foreach (string[] strArr in results)
                    {
                        ListViewItem item = new ListViewItem();
                        item.Text = strArr[0];
                        for (int i = 1; i < strArr.Length; i++)
                            item.SubItems.Add(strArr[i]);
                        lstItems.Items.Add(item);
                    }
                    lstItems.ResizeColumns();
                }
                catch (System.ServiceModel.CommunicationException exComm)
                {
                    System.Diagnostics.Debug.WriteLine(exComm);
                    MessageBox.Show("Request timed out. Please make sure you are connected to the internet and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    Program.LogError(this, ex);

                    MessageBox.Show("Your request cannot be completed.\nError details: " 
                        + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    btnSearch.Enabled = true;
                    lstItems.ResumeLayout();
                    this.ResumeLayout(true);
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (lstItems.SelectedItems.Count > 0)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    string[] keywords = new string[lstItems.Columns.Count];
                    ListViewItem lvItem = lstItems.SelectedItems[0];
                    if (lvItem.SubItems != null && lvItem.SubItems.Count > 0)
                    {
                        for (int i = 0; i < lvItem.SubItems.Count; i++)
                        {
                            keywords[i] = lvItem.SubItems[i].Text;
                        }
                    }

                    item =
                        webSearchPlugin.FindItem(keywords);

                    if (item == null)
                    {
                        MessageBox.Show("No results found.");
                        return;
                    }

                    this.DialogResult = DialogResult.OK;
                }
                catch (System.ServiceModel.CommunicationException exComm)
                {
                    System.Diagnostics.Debug.WriteLine(exComm);
                    MessageBox.Show("Your request cannot be completed.\nplease ensure you are connected to the internet and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    Program.LogError(this, ex);
                    MessageBox.Show("Your request cannot be completed.\nError details: "
                        + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private bool LoadWebSearchPlugin()
        {
            //Plugin info = PersistenceLayerFacade.GetCategoryPlugins((int)lstCategory.SelectedValue);
            Plugin info = PersistenceLayerFacade.GetCategoryPlugins((int)selectedCategory);

            object plugin =
                PluginManager.CreateInstance("IWebSearchPlugin", Application.StartupPath + "\\" + info.WebSearchPlugin);

            if (plugin != null)
            {
                webSearchPlugin = (IWebSearchPlugin)plugin;
                return true;
            }
            else
            {
                //MessageBox.Show(lstCategory.Text + " web search plugin is not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                MessageBox.Show(selectedCategory.ToString() + " web search plugin is not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private void lstItems_DoubleClick(object sender, EventArgs e)
        {
            if (lstItems.SelectedItems.Count > 0)
            {
                btnAdd_Click(sender, e);
            }
        }

    }
}
